import React, { useState } from "react";
import { useI18n } from '@/utils/in18';

// 作品详情弹窗组件：用于展示大图与详细信息，并提供公开设置与删除、点赞操作
// - 支持 PC 与移动端响应式布局
// - 支持暗黑模式（基于全局 `dark` class）

export type WorkItem = {
  id: number;
  image_url: string;
  display_prompt?: string | null;
  createdAt?: string;
  likes_count?: number;
  is_public?: boolean;
  downloads_count?: number;
  views_count?: number;
  is_liked?: boolean;
};

type Props = {
  open: boolean; // 是否展示弹窗
  work: WorkItem | null; // 当前查看的作品
  onClose: () => void; // 关闭弹窗
  onTogglePublic: (workId: number, nextPublic: boolean) => Promise<void>; // 切换公开/私密
  onDelete: (workId: number) => Promise<void>; // 删除作品
  onToggleLike: (workId: number) => Promise<void>; // 点赞/取消点赞
};

const WorkDetailModal: React.FC<Props> = ({ open, work, onClose, onTogglePublic, onDelete }) => {
  const [downloading, setDownloading] = useState(false);
  const [confirmKind, setConfirmKind] = useState<null | 'private' | 'delete'>(null);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const { t } = useI18n();

  if (!open || !work) return null;

  // 将 display_prompt 以逗号分隔转为标签数组
  const tags = (work.display_prompt || "")
    .split(",")
    .map((s) => s.trim())
    .filter(Boolean);

  // 预定义一组标签背景（支持暗黑模式）
  const tagBgClasses = [
    "bg-red-100 dark:bg-red-900",
    "bg-yellow-100 dark:bg-yellow-900",
    "bg-green-100 dark:bg-green-900",
    "bg-blue-100 dark:bg-blue-900",
    "bg-indigo-100 dark:bg-indigo-900",
    "bg-pink-100 dark:bg-pink-900",
    "bg-purple-100 dark:bg-purple-900",
    "bg-emerald-100 dark:bg-emerald-900",
  ];

  const createdDateStr = work.createdAt ? new Date(work.createdAt).toLocaleString() : "";

  // 使用 fetch 将图片转为 blob 后触发下载（兼容跨域时更可靠）
  const handleDownload = async (url: string, id: number) => {
    try {
      setDownloading(true);
      const resp = await fetch(url, { mode: 'cors' });
      if (!resp.ok) throw new Error('下载失败');
      const blob = await resp.blob();
      const ext = blob.type.split('/')[1] || 'jpg';
      const filename = `work_${id}.${ext}`;
      const blobUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = blobUrl;
      a.download = filename;
      document.body.appendChild(a);
      a.click();
      a.remove();
      URL.revokeObjectURL(blobUrl);
    } catch (e) {
      // 错误提示通过拦截器或上层处理，这里简单恢复状态
      console.error('download error', e);
    } finally {
      setDownloading(false);
    }
  };

  return (
    <div className="fixed inset-0 z-[10000] flex items-center justify-center p-4">
      {/* 背景遮罩 */}
      <div className="absolute inset-0 bg-black/60" onClick={onClose} />

      {/* 内容卡片：将 overflow-hidden 改为 overflow-auto，使内容可滚动 */}
      <div className="relative z-10 w-full max-w-5xl max-h-[90vh] overflow-auto rounded-2xl bg-white dark:bg-[#0b0b0b] text-gray-900 dark:text-gray-100 shadow-2xl border border-gray-200 dark:border-gray-700">
        {/* 头部 */}
        <div className="flex items-center justify-between px-4 sm:px-6 py-3 border-b border-gray-200 dark:border-gray-700">
          <div className="font-semibold">{t('my_work.work_details')}</div>
          <button onClick={onClose} className="px-2 py-1 rounded hover:bg-gray-100 dark:hover:bg-[#111]/60">{t('my_work.close')}</button>
        </div>

        {/* 主体：左右布局，移动端上下布局 */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-0 md:gap-4 max-h-[calc(90vh-56px)]">
          {/* 图片预览区 */}
          <div className="p-4 md:p-6 overflow-auto flex items-center justify-center bg-gray-50 dark:bg-[#0a0a0a]">
            <img
              src={work.image_url}
              alt="work"
              className="max-h-[60vh] md:max-h-[70vh] w-auto rounded-lg object-contain border border-gray-200 dark:border-gray-700"
            />
          </div>

          {/* 信息与操作区 */}
          <div className="p-4 md:p-6 overflow-auto">
            {/* 标签 */}
            <div className="flex flex-wrap gap-2">
              {tags.length > 0 ? (
                tags.map((tag, idx) => (
                  <span
                    key={idx}
                    className={`text-xs px-2 py-1 rounded-full border border-gray-200 dark:border-gray-700 ${tagBgClasses[idx % tagBgClasses.length]}`}
                  >
                    {tag}
                  </span>
                ))
              ) : (
                <span className="text-xs text-gray-500">{t('my_work.no_tags')}</span>
              )}
            </div>

            {/* 统计信息（添加图标） */}
            <div className="mt-4 grid grid-cols-2 gap-3 text-sm">
              <div className="flex flex-col p-3 rounded-lg bg-gray-50 dark:bg-[#0b0b0b] border border-gray-200 dark:border-gray-700">
                <div className="flex items-center gap-2">
                  {/* 时间图标 */}
                  <svg className="w-4 h-4 text-gray-500" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M12 7V12L15 14" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                    <path d="M21 12A9 9 0 1 1 3 12a9 9 0 0 1 18 0z" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                  <span className="text-gray-500 text-xs">{t('my_work.creation_time')}</span>
                </div>
                <span className="mt-1">{createdDateStr}</span>
              </div>
              <div className="flex flex-col p-3 rounded-lg bg-gray-50 dark:bg-[#0b0b0b] border border-gray-200 dark:border-gray-700">
                <div className="flex items-center gap-2">
                  {/* 点赞图标 */}
                  <svg className="w-4 h-4 text-gray-500" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 1 0-7.78 7.78L12 21.23l8.84-8.84a5.5 5.5 0 0 0 0-7.78z" stroke="currentColor" strokeWidth="0.5" fill="currentColor" />
                  </svg>
                  <span className="text-gray-500 text-xs">{t('my_work.number_of_likes')}</span>
                </div>
                <span className="mt-1">{work.likes_count ?? 0}</span>
              </div>
              <div className="flex flex-col p-3 rounded-lg bg-gray-50 dark:bg-[#0b0b0b] border border-gray-200 dark:border-gray-700">
                <div className="flex items-center gap-2">
                  {/* 下载图标 */}
                  <svg className="w-4 h-4 text-gray-500" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                    <path d="M7 10l5 5 5-5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                    <path d="M12 15V3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                  <span className="text-gray-500 text-xs">{t('my_work.number_of_downloads')}</span>
                </div>
                <span className="mt-1">{work.downloads_count ?? 0}</span>
              </div>
              <div className="flex flex-col p-3 rounded-lg bg-gray-50 dark:bg-[#0b0b0b] border border-gray-200 dark:border-gray-700">
                <div className="flex items-center gap-2">
                  {/* 浏览图标 */}
                  <svg className="w-4 h-4 text-gray-500" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12z" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                    <path d="M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                  <span className="text-gray-500 text-xs">{t('my_work.number_of_views')}</span>
                </div>
                <span className="mt-1">{work.views_count ?? 0}</span>
              </div>
            </div>

            {/* 操作按钮 */}
            <div className="mt-4 flex flex-wrap gap-3">
              <button
                className="px-4 py-2 text-sm rounded-lg border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-[#111]"
                onClick={() => {
                  const nextPublic = !work.is_public;
                  if (!nextPublic) {
                    setConfirmKind('private');
                  } else {
                    onTogglePublic(work.id, true);
                  }
                }}
              >
                {work.is_public ? t('my_work.set_as_private') : t('my_work.set_as_public')}
              </button>
              <button
                className="px-4 py-2 text-sm rounded-lg border border-red-200 text-red-600 hover:bg-red-50"
                onClick={() => setConfirmKind('delete')}
              >
                {t('my_work.delete')}
              </button>

              {/* 下载按钮 */}
              <button
                className="px-4 py-2 text-sm rounded-lg border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-[#111]"
                onClick={() => handleDownload(work.image_url, work.id)}
                disabled={downloading}
              >
                {downloading ? t('my_work.downloading') : t('my_work.download')}
              </button>
            </div>
          </div>
        </div>
         {/* 二次确认弹窗（全屏 fixed，遮罩完全覆盖；并阻止主体滚动） */}
         {confirmKind && (
           <div className="fixed inset-0 z-[20000] flex items-center justify-center p-4">
             <div className="absolute inset-0 bg-black/50" onClick={() => confirmLoading ? null : setConfirmKind(null)} />
             <div className="relative z-10 w-full max-w-sm rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-[#0b0b0b] p-4 shadow-xl">
              <div className="text-base font-semibold text-gray-900 dark:text-gray-100">
                {confirmKind === 'private' ? t('my_work.confirm_private_title') : t('my_work.confirm_delete_title')}
              </div>
              <div className="mt-2 text-sm text-gray-600 dark:text-gray-300">
                {confirmKind === 'private' ? t('my_work.confirm_private_desc') : t('my_work.confirm_delete_desc')}
              </div>
              <div className="mt-4 flex justify-end gap-2">
                <button
                  className="px-3 py-1.5 text-sm rounded border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-[#111]"
                  onClick={() => setConfirmKind(null)}
                  disabled={confirmLoading}
                >
                  {t('my_work.cancel')}
                </button>
                <button
                  className={`px-3 py-1.5 text-sm rounded ${confirmKind === 'delete' ? 'bg-red-600 text-white hover:opacity-90' : 'bg-primary text-white hover:opacity-90'}`}
                  onClick={async () => {
                    try {
                      setConfirmLoading(true);
                      if (confirmKind === 'private') {
                        await onTogglePublic(work.id, false);
                      } else if (confirmKind === 'delete') {
                        await onDelete(work.id);
                      }
                      setConfirmKind(null);
                    } finally {
                      setConfirmLoading(false);
                    }
                  }}
                  disabled={confirmLoading}
                >
                  {confirmLoading ? t('my_work.please_wait') : t('my_work.confirm')}
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default WorkDetailModal;


